package org.changchen.fgt.service.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.changchen.fgt.dto.HotVideoDto;
import org.changchen.fgt.service.IqiyiService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class IqiyiServiceImpl implements IqiyiService{
	
	
	@Override
	public List<HotVideoDto> rank(int limit) throws MalformedURLException, IOException {
		
		String url = "https://www.iqiyi.com/ranks1/-1/0";
		
		// parse解析URL
		Document doc = Jsoup.parse(new URL(url), 30000);
		Elements elements = doc.getElementsByClass("rvi__box");
		
		List<HotVideoDto> resultList = new ArrayList<>();
		for(int i=0; i < elements.size(); i++) {
			
			// 名称
			Elements titleElements = elements.get(i).getElementsByClass("rvi__tit1");
			if(CollectionUtil.isEmpty(titleElements)) {
				continue;
			}
			String title = titleElements.get(0).attr("title");
			
			// 图片
			Elements pictureElements = elements.get(i).getElementsByTag("picture");
			if(CollectionUtil.isEmpty(pictureElements)) {
				continue;
			}
			String picture = pictureElements.get(0).attr("id");
			
			// 图片链接加上https
			picture = String.format("https:%s", picture);
			
			HotVideoDto hotDto = new HotVideoDto();
			hotDto.setName(title);
			hotDto.setCover(picture);
			
			if(i < limit) {
				resultList.add(hotDto);
			}
			
		}
		
		return resultList;
	}
	

}
